import re

def process_files(en_path, cn_path, output_path):
    # 读取英文原版文件
    with open(en_path, 'r', encoding='utf-8') as f:
        en_lines = f.readlines()
    
    # 读取中文文件
    with open(cn_path, 'r', encoding='utf-8') as f:
        cn_lines = f.readlines()
    
    # 提取中文翻译映射和额外条目
    translations = {}
    extra_entries = []
    key_pattern = re.compile(r'^(\w[\w\d_]*)')
    
    for line in cn_lines:
        line = line.rstrip('\n')
        # 跳过注释行和空行
        if not line or line.startswith('#') or line.startswith(' '):
            continue
            
        # 尝试提取键名
        match = key_pattern.match(line)
        if match:
            key = match.group(1)
            # 获取等号/空格后的翻译部分（保留原始空格格式）
            value_part = line[len(key):].lstrip()
            
            # 检查是否为英文文件中的键
            found_in_en = any(re.match(f'^{key}\\b', en_line) for en_line in en_lines)
            
            if found_in_en:
                translations[key] = value_part
            else:
                extra_entries.append(line)
    
    # 处理英文文件内容
    output = []
    for line in en_lines:
        orig_line = line.rstrip('\n')
        match = key_pattern.match(orig_line)
        
        if match:
            key = match.group(1)
            # 保留英文原始空格格式
            if key in translations:
                indent_part = orig_line[len(key):]
                output.append(key + indent_part.replace(
                    orig_line[len(key):].lstrip(), 
                    translations[key]
                ))
                continue
                
        # 非键值行或未翻译行保持原样
        output.append(orig_line)
    
    # 添加额外条目
    if extra_entries:
        output.append('')  # 添加空行分隔
        output.extend(extra_entries)
    
    # 写入输出文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(output))

# 使用示例 (替换实际文件路径)
process_files('en.txt', 'cn.txt', 'output.txt')
